package com.zhiwu.uhf.util;

public class TagUtil {

    public static void main(String[] args) {
        TagUtil.init();
        System.out.println(TagUtil.Hex2Hex4NoSecrate(TagUtil.testStr));
    }
    public static String testStr = "FB6FF6CF1F93D00000000001";

    // readTag.init();先调用，给 positions 赋值
    // string A111 = readTag.Hex2Hex4NoSecrate(testStr);返回结果为001185
    static int[] positions = new int[16];
    public static void init()
    {
        int num = 0;
        int num2;
        for (int i = 5; i < 37; i = num2 + 1)
        {
            boolean flag = i % 2 == 0;
            if (flag)
            {
                int[] array = positions;
                num2 = num;
                num = num2 + 1;
                array[num2] = i;
            }
            num2 = i;
        }
    }
    public static String Hex2Hex4NoSecrate(String hexString)
    {
        String text = HexString2BinString(hexString);
        String f = getF(text.substring(0, 53));
        String text2 = "";
        int num;

        for (int i = 0; i < positions.length; i = num + 1)
        {
            text2 += f.substring(positions[i] + i, positions[i] + i + 2);
            num = i;
        }
        text2 = text2.substring(0, 31);

        String text3 = f.substring(0, 5) + text2 + "1111000011110000" + text.substring(52);
        return (BinString2HexString(text3.replace(" ", ""))).substring(2, 8);
    }


    static String HexString2BinString(String hexString)
    {
        String text = "";
        for (int i = 0; i < hexString.length(); i++)
        {
            char hexChar = hexString.charAt(i);
            int value = Character.digit(hexChar, 16);
            text += String.format("%4s", Integer.toBinaryString(value))
                    .replace(' ', '0');
        }
        return text;
    }

    static String getF(String str)
    {
        str = str.replace(" ", "");
        String r = "";
        for (int i = 0; i < str.length(); i++)
        {
            String subStr = str.substring(i, i + 1);
            r += String.valueOf(Short.parseShort(subStr) ^ 1);
        }
        return r.replace(" ", "");
    }

    static String BinString2HexString(String binString)
    {
        String text = "";
        int num;
        for (int i = 0; i < binString.length() / 4; i = num + 1)
        {
            text = text + " " + String.format("%d", Integer.parseInt(binString.substring(i * 4, i * 4 + 4), 2));
            num = i;
        }
        return text.replace(" ", "");
    }
}
